var css_attributes = [
'accelerator','azimuth',
'background','background-attachment',
'background-color',
'background-image',
'background-position',
'background-position-x',
'background-position-y',
'background-repeat',
'behavior',
	'border',
'border-bottom',
'border-bottom-color',
'border-bottom-style',
'border-bottom-width',
'border-collapse',
'border-color',
'border-left',
'border-left-color',
'border-left-style',
'border-left-width',
'border-radius',
	'border-right',
'border-right-color',
'border-right-style',
'border-right-width',
'border-spacing',
'border-style',
'border-top',
'border-top-color',
'border-top-style',
'border-top-width',
'border-width',
'bottom',
'color',
'font-family',
'font-size',
'margin',
'opacity'];

//
var dhxWins, layoutWin, dhxLayout, dhxTree, dhxAccord,
image_arr, 
pattern,	// pattern to make a new image icon by copying 
Element_class,
zIndexMax = 0, Image_count = 0, Text_count = 0, selectingId="";
elem_count = new Array();
function doOnLoad() {
    dhxWins = new dhtmlXWindows();
    dhxWins.enableAutoViewport(false);
    dhxWins.attachViewportTo("winVP");
    dhxWins.setImagePath("/static/dhtmlx/dhtmlxWindows/codebase/imgs/");
    dhxLayout = new dhtmlXLayoutObject(dhxWins.createWindow("w1", 20, 30, 800, 520), "2U", "");

    dhxWins.window("w1").setText("GREETING CARD MAKER");
    
    var toolbar = dhxWins.window("w1").attachToolbar();
    toolbar.setIconsPath("/static/dhtmlx/dhtmlxToolbar/samples/common/imgs/");
    toolbar.loadXML("/static/xml/general_toolbar.xml?" + new Date().getTime());
    
    toolbar.attachEvent("onClick", function(id){
    	if (id == "cut"){
    		delete_element(selectingId);
    	}
    });
}

$(document).ready(function() {
	
	/*
	 * General Layout design
	 */
	doOnLoad();
	dhxLayout.cells("a").setText("Tools");
	dhxLayout.cells("b").setText("Making Card");

	dhxLayout.cells("a").setWidth(250);
	dhxLayout.cells("b").attachObject("card");
	
	dhxTabbar = dhxLayout.cells("a").attachTabbar();
	dhxTabbar.setSkin('modern');
    dhxTabbar.setImagePath("/static/dhtmlx/dhtmlxTabbar/codebase/imgs/");
    
    dhxTabbar.addTab("tools","Tools","75px");
    dhxTabbar.addTab("tree","HTML-tree","75px");
    dhxTabbar.addTab("animations","Animations","75px");
    
    dhxTree = dhxTabbar.cells("tree").attachTree();
    dhxTree.setSkin('dhx_skyblue');
    dhxTree.setImagePath("/static/dhtmlx/dhtmlxTree/samples/common/images/");
    dhxTree.loadXML("/static/xml/tree.xml");
    dhxTree.setStdImages("book.gif", "books_open.gif", "books_close.gif");
    
    initialize_tree();	// basic_htmle.js
    
	dhxAccord = dhxTabbar.cells("tools").attachAccordion();
	dhxAccord.setSkin('dhx_blue');
	
	//dhxAccord.setSizes();
	dhxAccord.enableMultiMode();

	dhxAccord.addItem("a1", "Elements");
    dhxAccord.addItem("a2", "Attributes");
    //dhxAccord.addItem("a3", "Effects / Animations");
    
    // Attach toolbar to Accordion
    initialize_toolbar_a1();
    initialize_toolbar_a2();

    dhxAccord.cells("a1").setHeight("200");
    dhxAccord.cells("a2").setHeight("200");
    
    // create Tabbar for elements
    var ele_Tabbar = dhxAccord.cells("a1").attachTabbar();
    ele_Tabbar.setSkin('modern');
    ele_Tabbar.setImagePath("/static/dhtmlx/dhtmlxTabbar/codebase/imgs/");
	ele_Tabbar.addTab("a1","General","100px");
	ele_Tabbar.addTab("a2","Images","100px");
	
	ele_Tabbar.setContent("a1", "general-elements");
	ele_Tabbar.setContent("a2", "img-elements");
    
	ele_Tabbar.setTabActive("a1");
    //dhxAccord.cells("a1").attachObject("elements-container");
    dhxAccord.cells("a2").attachObject("attributes");
	
    // create Tabbar for attributes
	attr_Tabbar=new dhtmlXTabBar("attributes","top");
	attr_Tabbar.setSkin('modern');
	attr_Tabbar.setImagePath("/static/dhtmlx/dhtmlxTabbar/codebase/imgs/");
	//attr_Tabbar.addTab("a1","General","100px");
	attr_Tabbar.addTab("a2","Css-Properties","100px");
	attr_Tabbar.addTab("a3","Attributes","100px");
	
	attr_Tabbar.enableAutoReSize(true);
	
	//attr_Tabbar.setContent("a1", "general-attributes");
	attr_Tabbar.setContent("a2", "element-css-properties");
	attr_Tabbar.setContent("a3", "element-attributes");
	//attr_Tabbar.setTabActive("a1");
	
	// Menu
	dhxMenu = dhxWins.window("w1").attachMenu();
    dhxMenu.setIconsPath("/static/dhtmlx/dhtmlxMenu/samples/common/imgs/");
    dhxMenu.loadXML("/static/dhtmlx/dhtmlxMenu/samples/common/dhxmenu.xml?etc=" + new Date().getTime());
    
    /*
     * Tabbar for effects/animations
     */
    effect_Tabbar = dhxTabbar.cells("animations").attachTabbar();
    effect_Tabbar.setSkin('modern');
    effect_Tabbar.setImagePath("/static/dhtmlx/dhtmlxTabbar/codebase/imgs/");
	effect_Tabbar.addTab("a1","Start","100px");
	effect_Tabbar.addTab("a2","Interactive","100px");
	
	effect_Tabbar.setContent("a1", "general-animations");

	effect_Tabbar.setTabActive("a1");
	
	initialize_animation();

    /*
     * This is for own source-code writing part
     */
    $("div.jscode").resizable();
    $("div.jscode-button ul").click(function(e){
    	$("div#jscode").toggle("slow");
    });
    $("div.jscode .execode").click(function(e){
    	var code = $("div.jscode textarea").attr("value");
    	jQuery.globalEval(code);
    });
    /*
     * End source-code writing
     */
    
    // Make each element in list draggable 
	$("div#general-elements").children().draggable({
		revert: true,
		appendTo: "body",
		helper: 'clone',
		zIndex: 1000,
		cursor: "move",
		start: function(event, ui) {
	        $(ui.helper).width(200);
	    }

	});

	// Card body droppable
	$("div#card").droppable({
		accept: "div#img-elements img, div#general-elements div",
		hoverClass: "card-hover",
		drop: function(e, ui){
			//alert("dropped "+e.pageX);
			//alert(ui.draggable.attr("name"));
			var element = ui.draggable;
			if (element.attr("type") == "image")
				create_image(element.attr("name"), e.pageX, e.pageY);	// advanced_elements.js
			if (element.attr("type") == "text")
				create_text(e.pageX, e.pageY);
			if (element.attr("type") == "basic"){
				$( "#dialog-form" ).dialog( "open" );
				parentId = "card";
			}
		}
	});
	
	// Initialize dialog for adding new basic HTML element
	var parentId = "card";
	$( "#dialog-form" ).dialog({
		autoOpen: false,
		//height: 300,
		//width: 350,
		modal: true,
		buttons: {
			"Create": function() {
				var tag_name = $("#input_tag_name").val();
				var content = $("#input_content").val();
				
				insert_html_element(parentId, tag_name, {Text: content}, {color: "green"});
				$( this ).dialog( "close" );
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			//allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});

	// set overflow visible
	//$("div#general-elements").parents().css("overflow", "visible");
	
	// images list
	image_arr = image_list.split(",");
	
	pattern = $("div.img-icon").first();
	for (var i=0; i<image_arr.length - 1; i++){
		addNewImage(image_arr[i]);
	}
	
	
	// prepare for upload pic via Ajax
	init_upload();
	
	// create class for each element type
	//init_classes();
	
	/*
	 * Setup properties table
	 */
	 setup_functional_button();
	
	/*
	 * Choose the background image
	 */
	$("table td.background-image").droppable({
		accept: "div#img-elements img",
		hoverClass: "readyTodrop",
		drop: function(e, ui){
			var image_name = ui.draggable.attr("name");
			$(this).text(image_name);
			$("div#card").css("background-image", "url('/uploads/images/" + image_name + "')");
		}
	});
	
	$(document).mouseup( stopRotate );
	
	// delete element
	
	
	// Global array stores element objects
	
	// test autocomplete
});

// Create some Classes

function addNewImage(name){
	new_img = pattern.clone(true);
	new_img.children("img").attr("src","/uploads/images/thumb/" + name);
	new_img.children("img").attr("title", name);
	new_img.children("img").attr("name", name);
	new_img.children("img").attr("type", "image");
	
	if (name.length > 11) name = name.substring(0, 7) + "..";
	new_img.children("span").html(name);
	new_img.appendTo("div#img-elements");
	new_img.show();
	/**/
	new_img.children("img").draggable({
		revert: true,
		appendTo: "body",
		helper: 'clone',
		zIndex: 1000,
		cursor: "move"
	});
}

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

function initialize_animation(){
	
	/*
	 * setting for animation div pattern, ready to be used to copy
	 */
	$("div#animation-pattern div.element-id").mouseover(function(e){
		$(this).children("img").show();		// show delete button if exist
	});
	$("div#animation-pattern div.element-id").mouseout(function(e){
		$(this).children("img").hide();		// hide delete button if exist
	});
	$("img.delete-animation-button").click(function(){
		$(this).closest("div.animation").remove();
	});
	
	$("tr#option-pattern td").mouseover(function(e){
		$(this).children("img").show();		// show delete button if exist
	});
	$("tr#option-pattern td").mouseout(function(e){
		$(this).children("img").hide();		// hide delete button if exist
	});
	
	// Options table
	$("tr#option-pattern td").click(function(e){
		if ($(this).children().is("input")) return;
		
		var oldValue = $(this).text();
		
		// If Click on delete button
		if ($(e.target).attr("class") == "delete-option-button"){
			$(this).closest("tr").remove();
			return;
		}
		
		var close=null;
		if ($(this).hasClass("option")) close = $(this).children("img");
		
		$(this).text("");
		var input = $(document.createElement("input")).appendTo(this);
		input.attr("value", oldValue);
		input.attr("size", "10");
		/**/
		input.focus(function(){
			this.select();
			//alert("Selected");
		});
		input.focus();/**/
		
		var td = $(this); // The element clicked
		
		// Set the Css value of target element after Enter
		var setValue = function(e){
			var value = input.attr("value");
			td.text(value);
			input.remove();
			
			if (close){
				close.appendTo(td);
				close.hide();
			}
		};
		
		/**/
		input.blur(function(e){
			setValue(e);
		});
		/**/
		input.keypress(function(e){
			var code = (e.keyCode ? e.keyCode : e.which);
			if (code == 13) setValue(e);
		});
	});
	
	// Add option button
	$("div.animation ul.add-animation-option").click(function(){
		var tr = $("table tr#option-pattern").clone(true,true);
		
		tr.attr("id", "");
		tr.show();
		
		$(this).closest("div.animation").find("table").append(tr);
	});
	// Remove option
	$("div.animation ul.remove-animation-option").click(function(){
		$("div.animation table tr:last-child").remove();
	});
	
	// Animation name input
	/**/
	$("div.animation div.animation-name span.name").click(function(){
		if ($(this).children().is("input")) return;
		
		var oldValue = $(this).text();
		
		$(this).text("");
		var input = $(document.createElement("input")).appendTo(this);
		input.attr("value", oldValue);
		input.attr("size", "15");
		
		input.focus(function(){
			this.select();
			//alert("Selected");
		});
		input.focus();
		
		var td = $(this); // The element clicked
		
		// Set the Css value of target element after Enter
		var setValue = function(e){
			var value = input.attr("value");
			td.text(value);
			input.remove();
		};
		
		input.blur(function(e){
			setValue(e);
		});
		input.keypress(function(e){
			var code = (e.keyCode ? e.keyCode : e.which);
			if (code == 13) setValue(e);
		});
	});
	/**/
	
	// Add animation button
	$("ul.add-animation-button").click(function(e){
		if (selectingId == ""){ return;}
		
		var animDiv = $("div#animation-pattern").clone(true,true).attr("id", "").show();
		
		$("ul.add-animation-button").before(animDiv);
		
		animDiv.find("span.elem-id").text(selectingId);
	});
	
	// Play animation
	$("ul.play-animation").click(function(e){
		var animations = $(this).closest("div").children("div.animation:not(#animation-pattern)");
		execute_animations(animations);
	});
}

function initialize_toolbar_a1(){
	
	dhxAccord.dhxWins.enableAutoViewport(false);
    dhxAccord.dhxWins.attachViewportTo("winVP");
    dhxAccord.dhxWins.setSkin("dhx_skyblue");
	
	var toolbar_a1 = dhxAccord.cells("a1").attachToolbar();
    toolbar_a1.setSkin('dhx_blue');
    toolbar_a1.setIconsPath("/static/dhtmlx/dhtmlxToolbar/samples/common/imgs/");
    toolbar_a1.loadXML("/static/xml/toolbar_1.xml?" + new Date().getTime());
    
    // button click
    toolbar_a1.attachEvent("onClick", function(id){
    	if (id == "undock"){
    		dhxAccord.cells("a1").undock();
    		dhxAccord.dhxWins.window("a1").keepInViewport(true);
    	}
    });
}
function initialize_toolbar_a2(){
	
	var toolbar_a2 = dhxAccord.cells("a2").attachToolbar();
    toolbar_a2.setSkin('dhx_blue');
    toolbar_a2.setIconsPath("/static/dhtmlx/dhtmlxToolbar/samples/common/imgs/");
    toolbar_a2.loadXML("/static/xml/toolbar_1.xml?" + new Date().getTime());
    
    // button click
    toolbar_a2.attachEvent("onClick", function(id){
    	if (id == "undock"){
    		dhxAccord.cells("a2").undock();
    		dhxAccord.dhxWins.window("a2").keepInViewport(true);
    	}
    });
}

// Css Property table
function setup_functional_button(){
	
	
	// Add Property button
	$("ul.add-property-button").click(function(e){
		var table = $(this).closest("div").children("table.property-table");
		add_table_row(table, "Css Property", "Value", "css");
	});
	
	$("ul.add-attribute-button").click(function(e){
		var table = $(this).closest("div").children("table.attr-table");
		add_table_row(table, "Attribute", "Value", "attr");
	});
	
	$("ul.import-properties-button").click(function(e){
		$( "#import-css-form" ).dialog("open");
	});
	
	// Import Css dialog
	$( "#import-css-form" ).dialog({
		autoOpen: false,
		//height: 300,
		//width: 350,
		modal: true,
		open: function(event, ui){
			getStyleXml();	//	XmlParser.js
		},
		buttons: {
			"Apply": function() {
				//alert($("select#css-template").val());
				var styleId = $("select#css-template").val();
				var table = $("#"+selectingId).data("prop_table");
				addCssTemplate(table, styleId);	// XmlParser.js
				
				$( "#import-css-form" ).dialog("close");
			}
		},
		close: function() {
			//allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});
}
